import pygame
import random
import math
import sys
from typing import List, Tuple, Dict, Optional

# 初始化pygame
pygame.init()
pygame.mixer.init()

# 游戏常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
TANK_SIZE = 40
BULLET_SIZE = 8
ENEMY_SPEED = 2
PLAYER_SPEED = 5
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GRAY = (128, 128, 128)
BRICK_COLOR = (139, 69, 19)
STEEL_COLOR = (192, 192, 192)
WATER_COLOR = (0, 191, 255)
GRASS_COLOR = (0, 100, 0)

# 加载音效
try:
    shoot_sound = pygame.mixer.Sound("assets/shoot.wav")
    explosion_sound = pygame.mixer.Sound("assets/explosion.wav")
    powerup_sound = pygame.mixer.Sound("assets/powerup.wav")
    hit_sound = pygame.mixer.Sound("assets/hit.wav")
    pygame.mixer.music.load("assets/bgm.wav")
    pygame.mixer.music.set_volume(0.3)
    pygame.mixer.music.play(-1)
except:
    # 如果音效文件不存在，创建空的音效对象
    class DummySound:
        def play(self): pass
        def set_volume(self, vol): pass
    
    shoot_sound = DummySound()
    explosion_sound = DummySound()
    powerup_sound = DummySound()
    hit_sound = DummySound()

# 方向常量
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3

# 障碍物类型
BRICK = 1
STEEL = 2
WATER = 3
GRASS = 4

# 游戏状态
START = 0
PLAYING = 1
PAUSED = 2
GAME_OVER = 3
VICTORY = 4

class Tank:
    def __init__(self, x: int, y: int, color: Tuple[int, int, int], is_player: bool = False):
        self.x = x
        self.y = y
        self.color = color
        self.direction = UP
        self.speed = PLAYER_SPEED if is_player else ENEMY_SPEED
        self.is_player = is_player
        self.bullet_speed = 8
        self.bullet_power = 1
        self.max_health = 1 if is_player else 1
        self.health = self.max_health
        self.shoot_cooldown = 30 if is_player else 100
        self.last_shot = 0
        self.width = TANK_SIZE
        self.height = TANK_SIZE
        self.bullets = []
        self.can_shoot = True
        self.invincible = False
        self.invincible_timer = 0
        self.score = 0
        self.level = 1

    def move(self, direction: int, obstacles: List["Obstacle"]) -> None:
        old_x, old_y = self.x, self.y
        self.direction = direction
        
        if direction == UP:
            self.y -= self.speed
        elif direction == RIGHT:
            self.x += self.speed
        elif direction == DOWN:
            self.y += self.speed
        elif direction == LEFT:
            self.x -= self.speed
        
        # 边界检查
        if self.x < 0:
            self.x = 0
        elif self.x > SCREEN_WIDTH - self.width:
            self.x = SCREEN_WIDTH - self.width
        if self.y < 0:
            self.y = 0
        elif self.y > SCREEN_HEIGHT - self.height:
            self.y = SCREEN_HEIGHT - self.height
        
        # 碰撞检测
        if self.check_collision(obstacles):
            self.x, self.y = old_x, old_y

    def check_collision(self, obstacles: List["Obstacle"]) -> bool:
        tank_rect = pygame.Rect(self.x, self.y, self.width, self.height)
        for obstacle in obstacles:
            if obstacle.type == GRASS:  # 草不阻挡坦克
                continue
            if tank_rect.colliderect(obstacle.rect):
                return True
        return False

    def shoot(self, current_time: int) -> Optional["Bullet"]:
        if not self.can_shoot or current_time - self.last_shot < self.shoot_cooldown:
            return None
        
        self.last_shot = current_time
        shoot_sound.play()
        
        # 计算子弹初始位置（坦克中心）
        bullet_x = self.x + self.width // 2 - BULLET_SIZE // 2
        bullet_y = self.y + self.height // 2 - BULLET_SIZE // 2
        
        # 根据坦克方向调整子弹位置
        if self.direction == UP:
            bullet_y -= self.height // 2
        elif self.direction == RIGHT:
            bullet_x += self.width // 2
        elif self.direction == DOWN:
            bullet_y += self.height // 2
        elif self.direction == LEFT:
            bullet_x -= self.width // 2
        
        return Bullet(bullet_x, bullet_y, self.direction, self.bullet_speed, 
                     self.bullet_power, self.color, self.is_player)

    def draw(self, screen: pygame.Surface) -> None:
        # 绘制坦克主体
        pygame.draw.rect(screen, self.color, 
                         (self.x, self.y, self.width, self.height))
        
        # 绘制坦克炮管
        center_x = self.x + self.width // 2
        center_y = self.y + self.height // 2
        gun_length = self.width // 2
        
        if self.direction == UP:
            pygame.draw.line(screen, WHITE, (center_x, center_y), 
                             (center_x, center_y - gun_length), 3)
        elif self.direction == RIGHT:
            pygame.draw.line(screen, WHITE, (center_x, center_y), 
                             (center_x + gun_length, center_y), 3)
        elif self.direction == DOWN:
            pygame.draw.line(screen, WHITE, (center_x, center_y), 
                             (center_x, center_y + gun_length), 3)
        elif self.direction == LEFT:
            pygame.draw.line(screen, WHITE, (center_x, center_y), 
                             (center_x - gun_length, center_y), 3)
        
        # 无敌状态闪烁效果
        if self.invincible and (self.invincible_timer // 5) % 2 == 0:
            pygame.draw.rect(screen, YELLOW, 
                             (self.x, self.y, self.width, self.height), 2)

    def update(self, current_time: int) -> None:
        if self.invincible:
            self.invincible_timer -= 1
            if self.invincible_timer <= 0:
                self.invincible = False

    def take_damage(self, damage: int) -> bool:
        if self.invincible:
            return False
        
        self.health -= damage
        hit_sound.play()
        
        if self.health <= 0:
            explosion_sound.play()
            return True
        
        # 受伤后短暂无敌
        self.invincible = True
        self.invincible_timer = 120
        return False

    def upgrade(self) -> None:
        powerup_sound.play()
        self.level += 1
        self.bullet_power = min(3, self.level // 2 + 1)
        self.shoot_cooldown = max(15, 30 - (self.level - 1) * 3)
        self.speed = min(7, PLAYER_SPEED + (self.level - 1) // 3)

class Bullet:
    def __init__(self, x: int, y: int, direction: int, speed: int, power: int, 
                 color: Tuple[int, int, int], is_player: bool):
        self.x = x
        self.y = y
        self.direction = direction
        self.speed = speed
        self.power = power
        self.color = color
        self.is_player = is_player
        self.width = BULLET_SIZE
        self.height = BULLET_SIZE
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)

    def update(self) -> bool:
        if self.direction == UP:
            self.y -= self.speed
        elif self.direction == RIGHT:
            self.x += self.speed
        elif self.direction == DOWN:
            self.y += self.speed
        elif self.direction == LEFT:
            self.x -= self.speed
        
        # 更新矩形区域
        self.rect.x = self.x
        self.rect.y = self.y
        
        # 检查是否超出屏幕
        if (self.x < 0 or self.x > SCREEN_WIDTH or
            self.y < 0 or self.y > SCREEN_HEIGHT):
            return False
        return True

    def draw(self, screen: pygame.Surface) -> None:
        pygame.draw.rect(screen, self.color, self.rect)

    def check_collision(self, obstacles: List["Obstacle"]) -> Tuple[bool, Optional["Obstacle"]]:
        for obstacle in obstacles:
            if self.rect.colliderect(obstacle.rect):
                return True, obstacle
        return False, None

class Obstacle:
    def __init__(self, x: int, y: int, type: int):
        self.x = x
        self.y = y
        self.type = type
        self.width = TANK_SIZE
        self.height = TANK_SIZE
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        self.health = 1 if type == BRICK else float('inf')

    def take_damage(self, power: int) -> bool:
        if self.type == STEEL and power < 3:  # 钢墙需要3级子弹才能摧毁
            return False
        
        self.health -= power
        if self.health <= 0:
            if self.type == BRICK:
                explosion_sound.play()
            return True
        return False

    def draw(self, screen: pygame.Surface) -> None:
        if self.type == BRICK:
            pygame.draw.rect(screen, BRICK_COLOR, self.rect)
            # 砖块纹理
            for i in range(2):
                for j in range(2):
                    small_rect = pygame.Rect(
                        self.x + i * (self.width // 2),
                        self.y + j * (self.height // 2),
                        self.width // 2 - 1,
                        self.height // 2 - 1
                    )
                    pygame.draw.rect(screen, (160, 82, 45), small_rect)
        elif self.type == STEEL:
            pygame.draw.rect(screen, STEEL_COLOR, self.rect)
            # 钢墙纹理
            for i in range(3):
                pygame.draw.line(screen, GRAY, 
                                (self.x, self.y + i * (self.height // 3)),
                                (self.x + self.width, self.y + i * (self.height // 3)), 1)
                pygame.draw.line(screen, GRAY, 
                                (self.x + i * (self.width // 3), self.y),
                                (self.x + i * (self.width // 3), self.y + self.height), 1)
        elif self.type == WATER:
            pygame.draw.rect(screen, WATER_COLOR, self.rect)
            # 水波纹效果
            time = pygame.time.get_ticks()
            alpha = (abs(math.sin(time / 200)) * 100) + 155
            wave_color = (min(255, WATER_COLOR[0] + 50), 
                         min(255, WATER_COLOR[1] + 50), 
                         min(255, WATER_COLOR[2]))
            for i in range(4):
                offset = (time // 100 + i) % 4
                pygame.draw.arc(screen, wave_color, 
                               (self.x + offset * 3, self.y + i * (self.height // 4), 
                                self.width - offset * 6, self.height // 4 - 1), 
                               0, math.pi, 1)
        elif self.type == GRASS:
            pygame.draw.rect(screen, GRASS_COLOR, self.rect)
            # 草丛纹理
            for i in range(5):
                for j in range(5):
                    if (i + j) % 2 == 0:
                        pygame.draw.rect(screen, (0, 128, 0),
                                        (self.x + i * (self.width // 5),
                                         self.y + j * (self.height // 5),
                                         self.width // 5, self.height // 5))

class PowerUp:
    def __init__(self, x: int, y: int, type: str):
        self.x = x
        self.y = y
        self.type = type  # 'health', 'speed', 'power', 'shield'
        self.width = TANK_SIZE // 2
        self.height = TANK_SIZE // 2
        self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
        self.lifetime = 300  # 300帧 = 5秒
        
        # 不同类型的颜色
        self.colors = {
            'health': (255, 0, 0),
            'speed': (0, 255, 0),
            'power': (0, 0, 255),
            'shield': (255, 255, 0)
        }
        
        # 不同类型的图标
        self.icons = {
            'health': pygame.Rect(0, 0, self.width - 4, self.height - 4),
            'speed': [(self.x + self.width // 2, self.y), 
                     (self.x + self.width, self.y + self.height // 2),
                     (self.x + self.width // 2, self.y + self.height),
                     (self.x, self.y + self.height // 2)],
            'power': [(self.x + self.width // 2, self.y),
                     (self.x + self.width, self.y + self.height),
                     (self.x, self.y + self.height)],
            'shield': pygame.Rect(self.x + 2, self.y + 2, self.width - 4, self.height - 4)
        }

    def update(self) -> bool:
        self.lifetime -= 1
        return self.lifetime > 0

    def draw(self, screen: pygame.Surface) -> None:
        # 闪烁效果
        if self.lifetime % 30 < 15:
            color = self.colors[self.type]
            if self.type == 'health':
                pygame.draw.rect(screen, color, self.icons[self.type])
                pygame.draw.rect(screen, WHITE, self.rect, 1)
            elif self.type == 'speed':
                pygame.draw.polygon(screen, color, self.icons[self.type])
                pygame.draw.rect(screen, WHITE, self.rect, 1)
            elif self.type == 'power':
                pygame.draw.polygon(screen, color, self.icons[self.type])
                pygame.draw.rect(screen, WHITE, self.rect, 1)
            elif self.type == 'shield':
                pygame.draw.rect(screen, WHITE, self.rect, 1)
                pygame.draw.rect(screen, color, self.icons[self.type])

    def apply(self, player: Tank) -> None:
        powerup_sound.play()
        if self.type == 'health':
            player.health = min(player.max_health, player.health + 1)
        elif self.type == 'speed':
            player.speed = min(8, player.speed + 1)
        elif self.type == 'power':
            player.upgrade()
        elif self.type == 'shield':
            player.invincible = True
            player.invincible_timer = 300

class Enemy(Tank):
    def __init__(self, x: int, y: int, level: int = 1):
        colors = [RED, (255, 165, 0), (139, 0, 0), (178, 34, 34)]
        speed_multiplier = [1.0, 1.2, 1.5, 1.8]
        health_multiplier = [1, 2, 3, 5]
        bullet_power = [1, 1, 2, 2]
        
        # 根据关卡确定敌人等级
        enemy_level = min(3, (level - 1) // 3)
        
        super().__init__(x, y, colors[enemy_level], is_player=False)
        self.level = enemy_level + 1
        self.speed = ENEMY_SPEED * speed_multiplier[enemy_level]
        self.max_health = health_multiplier[enemy_level]
        self.health = self.max_health
        self.bullet_power = bullet_power[enemy_level]
        self.change_direction_timer = random.randint(60, 180)
        self.move_timer = 0
        self.points = 100 * self.level

    def update(self, current_time: int, obstacles: List[Obstacle], player: Tank) -> None:
        super().update(current_time)
        
        # 随机改变方向
        self.change_direction_timer -= 1
        if self.change_direction_timer <= 0:
            self.direction = random.randint(0, 3)
            self.change_direction_timer = random.randint(60, 180)
        
        # 移动
        old_x, old_y = self.x, self.y
        if self.direction == UP:
            self.y -= self.speed
        elif self.direction == RIGHT:
            self.x += self.speed
        elif self.direction == DOWN:
            self.y += self.speed
        elif self.direction == LEFT:
            self.x -= self.speed
        
        # 边界检查
        if self.x < 0:
            self.x = 0
            self.direction = random.choice([UP, DOWN, RIGHT])
        elif self.x > SCREEN_WIDTH - self.width:
            self.x = SCREEN_WIDTH - self.width
            self.direction = random.choice([UP, DOWN, LEFT])
        if self.y < 0:
            self.y = 0
            self.direction = random.choice([RIGHT, DOWN, LEFT])
        elif self.y > SCREEN_HEIGHT - self.height:
            self.y = SCREEN_HEIGHT - self.height
            self.direction = random.choice([UP, RIGHT, LEFT])
        
        # 碰撞检测
        if self.check_collision(obstacles):
            self.x, self.y = old_x, old_y
            self.direction = random.randint(0, 3)
        
        # 有一定概率向玩家射击
        if player and random.random() < 0.01:
            # 计算与玩家的方向
            dx = player.x - self.x
            dy = player.y - self.y
            
            if abs(dx) > abs(dy):
                self.direction = RIGHT if dx > 0 else LEFT
            else:
                self.direction = DOWN if dy > 0 else UP

class Game:
    def __init__(self):
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("坦克大战 - 无限关卡")
        self.clock = pygame.time.Clock()
        self.running = True
        self.state = START
        self.player = Tank(SCREEN_WIDTH // 2 - TANK_SIZE // 2, 
                          SCREEN_HEIGHT - TANK_SIZE * 2, BLUE, True)
        self.enemies = []
        self.obstacles = []
        self.bullets = []
        self.explosions = []
        self.powerups = []
        self.level = 1
        self.score = 0
        self.lives = 3
        self.font = pygame.font.SysFont("SimHei", 24)
        self.large_font = pygame.font.SysFont("SimHei", 48)
        self.enemies_spawned = 0
        self.enemies_per_level = 5 + self.level * 2
        self.spawn_timer = 0
        self.game_over_timer = 0
        self.victory_timer = 0
        
        # 加载背景图片
        self.background = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.background.fill(BLACK)
        
        # 绘制网格背景
        for x in range(0, SCREEN_WIDTH, TANK_SIZE):
            for y in range(0, SCREEN_HEIGHT, TANK_SIZE):
                pygame.draw.rect(self.background, (30, 30, 30), 
                                (x, y, TANK_SIZE, TANK_SIZE), 1)
        
        # 初始化第一关
        self.setup_level()

    def setup_level(self) -> None:
        """设置新关卡"""
        self.obstacles = []
        self.enemies = []
        self.bullets = []
        self.explosions = []
        self.powerups = []
        self.enemies_spawned = 0
        self.spawn_timer = 120  # 2秒后开始生成敌人
        
        # 生成障碍物
        self.generate_obstacles()
        
        # 重置玩家位置
        self.player.x = SCREEN_WIDTH // 2 - TANK_SIZE // 2
        self.player.y = SCREEN_HEIGHT - TANK_SIZE * 2
        self.player.direction = UP
        self.player.invincible = True
        self.player.invincible_timer = 180  # 3秒无敌时间
        
        # 更新关卡信息
        self.enemies_per_level = 5 + self.level * 2

    def generate_obstacles(self) -> None:
        """生成随机障碍物"""
        # 清空障碍物
        self.obstacles = []
        
        # 墙壁密度
        wall_density = 0.25 + min(0.2, self.level * 0.02)  # 随着关卡增加而增加
        steel_density = 0.1 + min(0.15, self.level * 0.01)  # 随着关卡增加而增加
        water_density = 0.1 + min(0.1, self.level * 0.005)  # 随着关卡增加而增加
        grass_density = 0.15
        
        # 生成墙壁
        for x in range(0, SCREEN_WIDTH, TANK_SIZE):
            for y in range(0, SCREEN_HEIGHT, TANK_SIZE):
                # 避开玩家出生点
                if (abs(x - self.player.x) < TANK_SIZE * 2 and 
                    abs(y - self.player.y) < TANK_SIZE * 2):
                    continue
                
                # 避开四个角落的敌人出生点
                enemy_spawns = [
                    (0, 0),
                    (SCREEN_WIDTH - TANK_SIZE, 0),
                    (0, TANK_SIZE * 2),
                    (SCREEN_WIDTH - TANK_SIZE, TANK_SIZE * 2)
                ]
                is_spawn_point = False
                for spawn_x, spawn_y in enemy_spawns:
                    if abs(x - spawn_x) < TANK_SIZE and abs(y - spawn_y) < TANK_SIZE:
                        is_spawn_point = True
                        break
                if is_spawn_point:
                    continue
                
                # 随机生成障碍物
                rand = random.random()
                if rand < wall_density:
                    if rand < steel_density:
                        self.obstacles.append(Obstacle(x, y, STEEL))
                    else:
                        self.obstacles.append(Obstacle(x, y, BRICK))
                elif rand < wall_density + water_density:
                    self.obstacles.append(Obstacle(x, y, WATER))
                elif rand < wall_density + water_density + grass_density:
                    self.obstacles.append(Obstacle(x, y, GRASS))

    def spawn_enemy(self) -> None:
        """生成敌人"""
        if self.enemies_spawned >= self.enemies_per_level:
            return
        
        # 四个角落随机选择一个出生点
        spawn_points = [
            (0, 0),
            (SCREEN_WIDTH - TANK_SIZE, 0),
            (0, TANK_SIZE * 2),
            (SCREEN_WIDTH - TANK_SIZE, TANK_SIZE * 2)
        ]
        spawn_x, spawn_y = random.choice(spawn_points)
        
        # 检查是否与障碍物碰撞
        for obstacle in self.obstacles:
            if (abs(spawn_x - obstacle.x) < TANK_SIZE and 
                abs(spawn_y - obstacle.y) < TANK_SIZE):
                return
        
        # 生成敌人
        enemy = Enemy(spawn_x, spawn_y, self.level)
        self.enemies.append(enemy)
        self.enemies_spawned += 1

    def handle_events(self) -> None:
        """处理游戏事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.running = False
                
                if self.state == START:
                    if event.key == pygame.K_SPACE:
                        self.state = PLAYING
                
                elif self.state == PLAYING:
                    if event.key == pygame.K_p:
                        self.state = PAUSED
                    
                    if event.key == pygame.K_SPACE:
                        bullet = self.player.shoot(pygame.time.get_ticks())
                        if bullet:
                            self.bullets.append(bullet)
                
                elif self.state == PAUSED:
                    if event.key == pygame.K_p:
                        self.state = PLAYING
                
                elif self.state == GAME_OVER or self.state == VICTORY:
                    if event.key == pygame.K_r:
                        self.__init__()  # 重新初始化游戏
    
    def handle_input(self) -> None:
        """处理玩家输入"""
        if self.state != PLAYING:
            return
            
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.player.move(UP, self.obstacles)
        elif keys[pygame.K_RIGHT]:
            self.player.move(RIGHT, self.obstacles)
        elif keys[pygame.K_DOWN]:
            self.player.move(DOWN, self.obstacles)
        elif keys[pygame.K_LEFT]:
            self.player.move(LEFT, self.obstacles)
    
    def update(self) -> None:
        """更新游戏状态"""
        if self.state != PLAYING:
            return
            
        current_time = pygame.time.get_ticks()
        
        # 更新玩家
        self.player.update(current_time)
        
        # 生成敌人
        self.spawn_timer -= 1
        if self.spawn_timer <= 0:
            self.spawn_enemy()
            self.spawn_timer = random.randint(60, 180)  # 1-3秒生成一个敌人
        
        # 更新敌人
        for enemy in self.enemies[:]:
            enemy.update(current_time, self.obstacles, self.player)
            
            # 敌人射击
            if random.random() < 0.005:  # 0.5%的概率射击
                bullet = enemy.shoot(current_time)
                if bullet:
                    self.bullets.append(bullet)
        
        # 更新子弹
        for bullet in self.bullets[:]:
            if not bullet.update():
                self.bullets.remove(bullet)
                continue
            
            # 检查子弹与障碍物的碰撞
            hit, obstacle = bullet.check_collision(self.obstacles)
            if hit:
                if obstacle.take_damage(bullet.power):
                    self.obstacles.remove(obstacle)
                    
                    # 有概率掉落道具
                    if random.random() < 0.1:
                        powerup_types = ['health', 'speed', 'power', 'shield']
                        powerup_type = random.choice(powerup_types)
                        self.powerups.append(PowerUp(obstacle.x, obstacle.y, powerup_type))
                
                self.bullets.remove(bullet)
                continue
            
            # 检查子弹与坦克的碰撞
            if bullet.is_player:
                for enemy in self.enemies[:]:
                    if bullet.rect.colliderect(enemy):
                        if enemy.take_damage(bullet.power):
                            self.enemies.remove(enemy)
                            self.score += enemy.points
                            
                            # 有概率生成道具
                            if random.random() < 0.2:
                                powerup_types = ['health', 'speed', 'power', 'shield']
                                powerup_type = random.choice(powerup_types)
                                self.powerups.append(PowerUp(enemy.x, enemy.y, powerup_type))
                        
                        self.bullets.remove(bullet)
                        break
            else:
                if bullet.rect.colliderect(self.player):
                    if self.player.take_damage(bullet.power):
                        self.lives -= 1
                        self.explosions.append((self.player.x, self.player.y))
                        
                        if self.lives <= 0:
                            self.state = GAME_OVER
                            self.game_over_timer = 180
                        else:
                            # 玩家重生
                            self.player.x = SCREEN_WIDTH // 2 - TANK_SIZE // 2
                            self.player.y = SCREEN_HEIGHT - TANK_SIZE * 2
                            self.player.direction = UP
                            self.player.health = self.player.max_health
                            self.player.invincible = True
                            self.player.invincible_timer = 180  # 3秒无敌时间
                    
                    self.bullets.remove(bullet)
        
        # 更新道具
        for powerup in self.powerups[:]:
            if not powerup.update():
                self.powerups.remove(powerup)
                continue
            
            # 检查玩家是否吃到道具
            if pygame.Rect(powerup.x, powerup.y, powerup.width, powerup.height).colliderect(
                pygame.Rect(self.player.x, self.player.y, self.player.width, self.player.height)):
                powerup.apply(self.player)
                self.powerups.remove(powerup)
        
        # 检查关卡是否完成
        if not self.enemies and self.enemies_spawned >= self.enemies_per_level:
            self.level += 1
            self.state = VICTORY
            self.victory_timer = 180  # 3秒后进入下一关
    
    def draw(self) -> None:
        """绘制游戏画面"""
        # 绘制背景
        self.screen.blit(self.background, (0, 0))
        
        # 绘制障碍物
        for obstacle in self.obstacles:
            obstacle.draw(self.screen)
        
        # 绘制道具
        for powerup in self.powerups:
            powerup.draw(self.screen)
        
        # 绘制子弹
        for bullet in self.bullets:
            bullet.draw(self.screen)
        
        # 绘制敌人
        for enemy in self.enemies:
            enemy.draw(self.screen)
        
        # 绘制玩家
        self.player.draw(self.screen)
        
        # 绘制爆炸效果
        for explosion in self.explosions[:]:
            x, y = explosion
            size = 50
            alpha = 255
            for i in range(5):
                pygame.draw.circle(
                    self.screen,
                    (255, 255 - i * 50, 0, alpha - i * 50),
                    (x + TANK_SIZE // 2, y + TANK_SIZE // 2),
                    size - i * 10
                )
            self.explosions.remove(explosion)
        
        # 绘制UI
        self.draw_ui()
        
        # 绘制游戏状态
        if self.state == START:
            self.draw_start_screen()
        elif self.state == PAUSED:
            self.draw_pause_screen()
        elif self.state == GAME_OVER:
            self.draw_game_over_screen()
        elif self.state == VICTORY:
            self.draw_victory_screen()
        
        pygame.display.flip()
    
    def draw_ui(self) -> None:
        """绘制游戏UI"""
        # 绘制分数
        score_text = self.font.render(f"分数: {self.score}", True, WHITE)
        self.screen.blit(score_text, (10, 10))
        
        # 绘制关卡
        level_text = self.font.render(f"关卡: {self.level}", True, WHITE)
        self.screen.blit(level_text, (10, 40))
        
        # 绘制生命值
        lives_text = self.font.render(f"生命: {self.lives}", True, WHITE)
        self.screen.blit(lives_text, (10, 70))
        
        # 绘制玩家等级
        level_text = self.font.render(f"等级: {self.player.level}", True, WHITE)
        self.screen.blit(level_text, (10, 100))
        
        # 绘制剩余敌人
        enemies_left = self.enemies_per_level - self.enemies_spawned + len(self.enemies)
        enemies_text = self.font.render(f"敌人: {enemies_left}", True, WHITE)
        self.screen.blit(enemies_text, (SCREEN_WIDTH - 120, 10))
        
        # 绘制玩家子弹等级
        bullet_text = self.font.render(f"子弹: {self.player.bullet_power}/3", True, WHITE)
        self.screen.blit(bullet_text, (SCREEN_WIDTH - 120, 40))
        
        # 绘制无敌状态
        if self.player.invincible:
            invincibility_text = self.font.render(
                f"无敌: {max(0, self.player.invincible_timer // 60)}s", 
                True, YELLOW
            )
            self.screen.blit(invincibility_text, (SCREEN_WIDTH - 120, 70))
    
    def draw_start_screen(self) -> None:
        """绘制开始屏幕"""
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        self.screen.blit(overlay, (0, 0))
        
        title = self.large_font.render("坦克大战 - 无限关卡", True, WHITE)
        subtitle = self.font.render("按空格键开始游戏", True, WHITE)
        instructions = self.font.render("使用方向键移动，空格键射击", True, WHITE)
        levels = self.font.render("关卡会随时间无限生成，难度逐渐增加", True, WHITE)
        
        self.screen.blit(title, (SCREEN_WIDTH // 2 - title.get_width() // 2, 
                                 SCREEN_HEIGHT // 2 - 100))
        self.screen.blit(subtitle, (SCREEN_WIDTH // 2 - subtitle.get_width() // 2, 
                                    SCREEN_HEIGHT // 2))
        self.screen.blit(instructions, (SCREEN_WIDTH // 2 - instructions.get_width() // 2, 
                                       SCREEN_HEIGHT // 2 + 50))
        self.screen.blit(levels, (SCREEN_WIDTH // 2 - levels.get_width() // 2, 
                                SCREEN_HEIGHT // 2 + 100))
    
    def draw_pause_screen(self) -> None:
        """绘制暂停屏幕"""
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        self.screen.blit(overlay, (0, 0))
        
        title = self.large_font.render("游戏暂停", True, WHITE)
        subtitle = self.font.render("按P键继续游戏", True, WHITE)
        
        self.screen.blit(title, (SCREEN_WIDTH // 2 - title.get_width() // 2, 
                                 SCREEN_HEIGHT // 2 - 50))
        self.screen.blit(subtitle, (SCREEN_WIDTH // 2 - subtitle.get_width() // 2, 
                                    SCREEN_HEIGHT // 2 + 20))
    
    def draw_game_over_screen(self) -> None:
        """绘制游戏结束屏幕"""
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        self.screen.blit(overlay, (0, 0))
        
        title = self.large_font.render("游戏结束", True, RED)
        score_text = self.font.render(f"最终分数: {self.score}", True, WHITE)
        level_text = self.font.render(f"最高关卡: {self.level}", True, WHITE)
        restart_text = self.font.render("按R键重新开始", True, WHITE)
        
        self.screen.blit(title, (SCREEN_WIDTH // 2 - title.get_width() // 2, 
                                 SCREEN_HEIGHT // 2 - 100))
        self.screen.blit(score_text, (SCREEN_WIDTH // 2 - score_text.get_width() // 2, 
                                     SCREEN_HEIGHT // 2 - 20))
        self.screen.blit(level_text, (SCREEN_WIDTH // 2 - level_text.get_width() // 2, 
                                     SCREEN_HEIGHT // 2 + 30))
        self.screen.blit(restart_text, (SCREEN_WIDTH // 2 - restart_text.get_width() // 2, 
                                       SCREEN_HEIGHT // 2 + 80))
    
    def draw_victory_screen(self) -> None:
        """绘制胜利屏幕"""
        overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
        overlay.fill((0, 0, 0, 180))
        self.screen.blit(overlay, (0, 0))
        
        title = self.large_font.render(f"第 {self.level-1} 关完成!", True, GREEN)
        score_text = self.font.render(f"当前分数: {self.score}", True, WHITE)
        next_level_text = self.font.render(f"准备进入第 {self.level} 关...", True, WHITE)
        
        self.screen.blit(title, (SCREEN_WIDTH // 2 - title.get_width() // 2, 
                                 SCREEN_HEIGHT // 2 - 80))
        self.screen.blit(score_text, (SCREEN_WIDTH // 2 - score_text.get_width() // 2, 
                                     SCREEN_HEIGHT // 2 - 10))
        self.screen.blit(next_level_text, (SCREEN_WIDTH // 2 - next_level_text.get_width() // 2, 
                                          SCREEN_HEIGHT // 2 + 40))
        
        # 倒计时
        countdown = self.font.render(
            f"{max(0, self.victory_timer // 60)}", 
            True, YELLOW
        )
        self.screen.blit(countdown, (SCREEN_WIDTH // 2 - countdown.get_width() // 2, 
                                    SCREEN_HEIGHT // 2 + 100))
        
        # 更新计时器
        self.victory_timer -= 1
        if self.victory_timer <= 0:
            self.state = PLAYING
            self.setup_level()
    
    def run(self) -> None:
        """运行游戏主循环"""
        while self.running:
            self.handle_events()
            
            if self.state == PLAYING:
                self.handle_input()
                self.update()
            
            self.draw()
            self.clock.tick(FPS)

if __name__ == "__main__":
    game = Game()
    game.run()
    pygame.quit()
    sys.exit()    